<?php
/*
 * 用户列表
 */
namespace app\admin\controller;
use app\common\controller\AdminBase;
use think\facade\Db;
use app\common\model\User as UserModel;

class User extends AdminBase
{

    protected function _initialize()
    {
        parent::_initialize();
    }

    public function lists()
    {
        $data['pwd'] = config("app.default_pwd");//默认密码
        $param = $this->request->param();
        if (!empty($param['title'])){
            $where = function ($query) use ($param){$query->where('name|mobile','LIKE', '%'.trim($param['title']).'%');};
        }else{
            $where = 1;
        }
        $list = UserModel::getUserList($where);
        $data['rank_name'] = Db::table('rank')->order('growth','ASC')->value('name');
        return $this->fetch('index', ['data'=>$data,'list'=>$list]);
    }

    public function add()
    {
        if ($this->request->isPost())
        {
            $param = $this->request->param();
            //验证规则
            $verify = input('_verify', true);
            if($verify!='0'){
                try{
                    $this->validate($param, 'user');
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
            }
            empty($param['password']) && $param['password'] = config("app.default_pwd");
            $param['plain_code'] = $param['password'];//明文密码
            $pwd = morse_code($param['plain_code']);
            $param['password'] = $pwd['password'];//密码
            $param['salt'] = $pwd['salt'];//盐
            $result = UserModel::create($param);
            !$result && $this->error($this->errorMsg);
            insert_admin_log('添加了用户');
            $this->success('添加成功');
        }
        return $this->fetch('save', ['rank' => Db::table('rank')->where('status',1)->select()]);
    }

    public function edit()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            if (empty($param['password'])) {
                unset($param['password'],$param['plain_code']);
            }else{
                $param['plain_code'] = $param['password'];//明文密码
                $pwd = morse_code($param['plain_code']);
	            $param['password'] = $pwd['password'];//密码
	            $param['salt'] = $pwd['salt'];//盐
            }
            $result = UserModel::update($param);
            !$result && $this->error($this->errorMsg);
            insert_admin_log('修改了用户');
            $this->success('修改成功', url('index'));
        }
        $data = UserModel::where('id', input('id'))->find();
        return $this->fetch('save', [
            'data' => $data,
            'rank' => Db::table('rank')->where('status',1)->select()]);
    }
    //账户明细
    public function log()
    {
        $list = Db::table('account')
            ->alias('a')
            ->leftJoin('user u','a.user_id = u.id')
            ->field('a.*,u.mobile,u.name')
            ->where('user_id',input('id'))->order('create_time','DESC')->paginate();
        return $this->fetch('log',['list'=>$list]);
    }

    //调节账户
    public function account()
    {
    	$info = UserModel::where('id', input('id'))->find();
        if ($this->request->isPost())
        {
            $param = $this->request->param();
            //验证规则
            $verify = input('_verify', true);
            if($verify!='0'){
                try{
                    $this->validate($param, 'account');
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
            }
            $param['uid'] = $param['id'];
            $param['change_type'] = 1;//管理员调节
            //执行插入操作
            $result = insert_account_log($param);
            !$result && $this->error($this->errorMsg);
            insert_admin_log('调节了用户 【'.$info['name'].'】 的账户');
            $this->success('调节成功');
        }
        return $this->fetch('account',['info'=>$info]);
    }
    //删除会员
    public function del()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            Db::table('account')->where('user_id',$param['id'])->find() && $this->error('用户下有账目记录，无法删除');
            Db::table('orders')->where('user_id',$param['id'])->find() && $this->error('用户下有订单，无法删除');
            UserModel::destroy($param['id']);
            insert_admin_log('删除了用户');
            $this->success('删除成功');
        }
    }
    //重置密码
    public function reset()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $param['plain_code'] = $param['password']= config("app.default_pwd");
            $pwd = morse_code($param['plain_code']);
            $param['password'] = $pwd['password'];//密码
            $param['salt'] = $pwd['salt'];//盐
            $result = UserModel::update($param);
            !$result && $this->error($this->errorMsg);
            insert_admin_log('重置了用户'.$param['id'].'的密码');
            $this->success('重置成功');
        }
    }

    //查询请求日志
    public function visit_lists()
    {
        $list = Db::table('see_log')
        ->withAttr('create_time', function($value) {  // 动态获取器
            return date('Y-m-d H:i:s',$value);
        })
        ->order('create_time','DESC')
        ->paginate();
        return $this->fetch('see', ['list'=>$list]);
    }
    //导出会员信息
    public function export()
    {
        $param = $this->request->param();
        if (!empty($param['title'])) {
            $name = trim($param['title']);
            $where = function ($query) use ($name){$query->where('name|mobile','LIKE', '%'.$name.'%');};
        }else{
            $where = 1;
        }
        $filename = date('YmdHis').'会员导出';
        $title = ['编号','手机号','性别','等级','姓名','身份证号','邮箱','余额','成长值','积分','转账状态','激活状态','状态'];
        $data = Db::table('user')
        ->alias('u')
        ->leftJoin('rank r','u.rank_id = r.id')
        ->field('u.name,u.mobile,u.gender,r.name rank_name,u.real_name,u.idcard,u.email,u.money,u.growth,u.integral,u.is_frozen,u.is_active,u.status')
        ->withAttr('gender', function($value) {  // 动态获取器
            $status = ['保密','男','女'];
            return $status[$value];
        })
        ->withAttr('status', function($value) {  // 动态获取器
            $status = ['禁用','正常'];
            return $status[$value];
        })
        ->withAttr('is_frozen', function($value) {  // 动态获取器
            $is_frozen = ['禁转','正常'];
            return $is_frozen[$value];
        })
        ->withAttr('is_active', function($value) {  // 动态获取器
            $is_active = ['未激活','已激活'];
            return $is_active[$value];
        })
        ->whereOr($where)
        ->select()
        ->toArray();
        export_excel($data, $title,$filename);
    }


}